add function replace_nodes to Tree#1524
Conversation
This can be used to replace tokens in a `Tree` that satisfy a specified rule.
|
Add tests. |
added 388fd80 |
|
Let's call it Also in the tests, you are changing |
|
*deepcopy |
|
|
@MegaIng Do we really need the special behavior for None? The callback can just return the parameter as is, if no changes are necessary. (I don't think it matters in terms of performance) |
|
True, probably not needed. To get the type checking to work:
This slightly changes the semantics, but I think it's more useful. |
…30/lark into feat/add_replace_node_func
|
|
Tbh I'm not convinced this is a useful method. I can't imagine many situations where it's desirable. But here's how it should look, if it was ever accepted: (more or less) def replace_values(self, replacer: 'Callable[[_Leaf_T], _Leaf_T]') -> None:
"""Replace all leaf values in the tree using the result of ``replacer(value)``.
The callback receives each leaf and should return its replacement,
or the same value unchanged if no replacement is desired.
Example:
>>> tree.replace_values(lambda v: v.update(value="y") if v == "x" else v)
"""
for index, child in enumerate(self.children):
if isinstance(child, Tree):
child.replace_values(replacer)
else:
result = replacer(child)
if result is not child:
self.children[index] = result |
This can be used to replace tokens in a
Treethat satisfy a specified rule.